<template>
  <div>
    <el-row>
      <p class="pinformation">方案列表</p>
      <p class="totalStyle">共 {{ total }} 条数据</p>
    </el-row>
    <el-table ref="mainTableRef" :data="projectList" v-loading="loading">
      <el-table-column prop="projectCode" label="方案编号" align="center" width="100" />
      <el-table-column prop="projectName" label="方案名称" align="center" />
      <el-table-column prop="wtCustomName" label="委托单位" align="center" width="250" />
      <el-table-column prop="wtAddress" label="委托单位地址" align="center" width="250" />
      <el-table-column prop="planDate" label="计划开始时间" align="center" width="110" />
      <el-table-column prop="endTime" label="计划完成时间" align="center" width="110" />
      <el-table-column label="方案类型" align="center" width="220">
        <template #default="scope">
          <dict-tag :options="sys_contract_type" :value="scope.row.contractType" />
        </template>
      </el-table-column>
      <el-table-column prop="sampleDay" label="连测天数" align="center" width="80" />
      <el-table-column
        prop="cyUserName"
        label="采样人员"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column prop label="操作" align="center" width="150">
        <template #default="scope">
          <el-button link type="success" @click="distribution(scope.row)">分配</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- search -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="seachForm.pageNum"
      v-model:limit="seachForm.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :class="'el-dialog-theme3'"
      v-model="open"
      :title="title"
      append-to-body
      draggable
      :close-on-click-modal="false"
      @close="closedDialog"
      width="1200"
    >
      <el-form label-width="100" :model="form" :rules="rules" ref="dialogFormRef">
        <el-row>
          <el-col :span="6">
            <el-form-item label="计划开始日期：">{{
              form.planDate
            }}</el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="方案编号：" label-width="70px">{{
              form.projectCode
            }}</el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="方案名称：" label-width="70px">{{
              form.projectName
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="委托单位：">{{ form.wtCustomName }}</el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="委托单位地址：">{{ form.wtAddress }}</el-form-item>
          </el-col>
        </el-row>
        <p class="pinformation">方案列表</p>
        <el-row>
          <el-col :span="11">
            <el-form-item label="点位名称：">
              <el-input
                v-model="searchCriteria.pointName"
                clearable
                @keyup.enter="search"
                placeholder="请输入点位名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="第几天：">
              <el-input
                v-model="searchCriteria.currentDay"
                clearable
                @keyup.enter="search"
                placeholder="第几天"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-row justify="end">
              <el-button type="success" @click="search">搜索</el-button>
              <el-button class="business resetBtn" @click="resetForm">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
        <el-row>
          <p class="pinformation">当日点位列表</p>
          <p class="totalStyle">共 {{ currentDayPointList.length }} 条数据</p>
        </el-row>
        <el-table
          :data="currentDayPointList"
          max-height="15vw"
          @selection-change="onAddSelect"
          ref="currentDayPointRef"
          row-key="cyId"
          v-loading="loading1"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :reserve-selection="true"
          />
          <el-table-column
            prop="point.pointName"
            label="点位名称"
            align="center"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="jclbId"
            label="检测类型"
            align="center"
            width="150"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ proxy.getItemByArray(jclbList, "jclbId", scope.row.jclbId, "jclbName") }}
            </template>
          </el-table-column>
          <el-table-column prop="sumDay" label="连测天数" align="center" width="100" />
          <el-table-column prop="currentDay" label="第几天" align="center" width="100" />
          <el-table-column prop="cyDate" label="计划日期" align="center" width="120" />
          <el-table-column
            prop="fpcyy"
            label="分配采样员"
            align="center"
            show-overflow-tooltip
          />
        </el-table>
        <el-row style="margin-top: 10px">
          <el-col :span="9">
            <el-form-item label="调整日期：" prop="cyDate">
              <el-date-picker
                v-model="form.cyDate"
                value-format="YYYY-MM-DD"
                :clearable="false"
                :editable="false"
                :picker-options="false"
                placeholder="调整日期"
                @change="cyDateChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label-width="0">
              {{
                "当日已安排" +
                countForm.projectCount +
                "个方案，" +
                countForm.pointCount +
                "个点位"
              }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="选择采样员：" prop="cyUserIds">
              <el-select
                v-model="form.cyUserIds"
                multiple
                filterable
                :disabled="!form.cyDate"
                style="width: 100%"
              >
                <el-option
                  v-for="item in cyUserList"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.nickName"
                >
                  <span style="float: left; margin-right: 20px">{{ item.nickName }}</span>
                  <span style="float: right">{{ item.remark }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="1">
            <el-button type="success" @click="define">确定</el-button>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="open = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getDialogFormDate,
  getDialogListDate,
  getDialogUserList,
  putDialogDate,
  getDialogCount,
} from "@/api/project/projectPlan";
import bus from "@/utils/eventBus";
import { complete } from "@/api/flowable/todo";
import { allListJclb } from "@/api/store/jclb";
import { getCytask } from "@/api/project/projectCheck";

const { proxy } = getCurrentInstance();
const { sys_contract_type } = proxy.useOrgDict("sys_contract_type");
const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);

const route = useRoute();
const total = ref(0);
const projectList = ref([]);
const open = ref(false);
const loading = ref(false);
const loading1 = ref(false);
const currentDayPointList = ref([]);
const cyUserList = ref([]);
const seachForm = ref({
  pageSize: 10,
  pageNum: 1,
});

const title = ref("日期人员调整");
const data = reactive({
  form: {
    contract: {},
  },
  searchCriteria: {},
  rules: {
    cyDate: [{ required: true, message: "调整日期不能为空", trigger: "blur" }],
    cyUserIds: [{ required: true, message: "分配采样员不能为空", trigger: "blur" }],
  },
});
const { form, searchCriteria, rules } = toRefs(data);
const props = defineProps({
  queryParams: {
    type: Object,
  },
});

const jclbList = ref([]);
allListJclb().then((res) => {
  jclbList.value = res.data;
});

function distribution(row) {
  open.value = true;
  getDialogFormDate(row.projectId).then((res) => {
    form.value = res.data;
    form.value.cyIds = [];
    if (!form.value.cyDate) {
      form.value.cyDate = form.value.planDate
        .replace("年", "-")
        .replace("月", "-")
        .replace("日", "");
    }
    cyDateChange();
    searchCriteria.value.projectId = res.data.projectId;
    search().then((res) => {
      proxy.$refs["currentDayPointRef"].clearSelection();
      proxy.$refs["currentDayPointRef"].toggleAllSelection();
    });
  });
}

function search() {
  return new Promise((resolve, reject) => {
    searchCriteria.value = {
      projectId: searchCriteria.value.projectId,
      "point.pointName": searchCriteria.value.pointName,
      pointName: searchCriteria.value.pointName,
      currentDay: searchCriteria.value.currentDay,
    };
    loading1.value = true;
    getDialogListDate(searchCriteria.value)
      .then((res) => {
        resolve();
        currentDayPointList.value = res.data;
        currentDayPointList.value.forEach((item, index) => {
          var temp = item.taskUserList.map((row) => {
            return row.cyUserName;
          });
          currentDayPointList.value[index].fpcyy = temp.join("、");
        });
        loading1.value = false;
      })
      .catch(() => {
        reject();
        loading1.value = false;
      });
  });
}

function onAddSelect(selection) {
  form.value.cyIds = selection.map((item) => {
    return item.cyId;
  });
  var previous = "";
  for (let i = 0; i < selection.length; i++) {
    let temp = "";
    let tempcyUserNames = selection[i].taskUserList.map((item1) => {
      return item1.cyUserName;
    });
    let tempUserIds = selection[i].taskUserList.map((item1) => {
      return item1.cyUserId;
    });
    temp = tempcyUserNames.join("、");
    if (previous == "") {
      previous = temp;
    }
    if (temp !== previous) {
      form.value.cyUserIds = [];
      break;
    } else {
      form.value.cyUserIds = tempUserIds;
    }
  }
  if (!selection.length) {
    form.value.cyUserIds = [];
  }
}

const routeProjectId = ref("");

function define() {
  if (form.value.cyUserIds.length == 1) {
    proxy.$modal.msgError("至少选择2个采样员！");
    return;
  }
  if (form.value.cyIds.length > 0) {
    proxy.$refs["dialogFormRef"].validate(async (valid) => {
      if (valid) {
        var temp = {
          cyDate: form.value.cyDate,
          cyUserIds: form.value.cyUserIds,
          cyIds: form.value.cyIds,
        };
        putDialogDate(temp).then((res) => {
          getList();
          search().then((res) => {
            proxy.$refs["currentDayPointRef"].clearSelection();
            proxy.$refs["currentDayPointRef"].toggleAllSelection();
          });
          if (routeProjectId.value == searchCriteria.value.projectId) {
            routeProjectId.value = "";
          } else {
            proxy.$modal.msgSuccess(res.msg);
          }
          bus.emit("dbSave", true);
        });
      }
    });
  } else {
    proxy.$modal.msgError("选择要分配的检测点位！");
  }
}

const countForm = ref({ projectCount: 0, pointCount: 0 });
function cyDateChange() {
  countForm.value = { projectCount: 0, pointCount: 0 };
  getDialogUserList(form.value.cyDate).then((res) => {
    cyUserList.value = res.data;
  });
  getDialogCount(form.value.cyDate).then((res) => {
    countForm.value = res.data;
  });
}

function resetForm() {
  delete searchCriteria.value.pointName;
  delete searchCriteria.value.currentDay;
  search();
}

function closedDialog() {
  form.value = { contract: {} };
  searchCriteria.value = {};
  currentDayPointList.value = [];
}

function getList() {
  let temp = props.queryParams;
  temp.pageNum = seachForm.value.pageNum;
  temp.pageSize = seachForm.value.pageSize;
  loading.value = true;
  getCytask(temp).then((res) => {
    projectList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
}

defineExpose({
  getList,
});

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

watch(
  () => route.query.projectId,
  () => {
    nextTick(() => {
      if (!route.query.projectId) {
        routeProjectId.value = "";
      } else {
        if (route.path == "/project/projectPlan") {
          routeProjectId.value = route.query.projectId.split("_")[1];
          let row = { projectId: route.query.projectId.split("_")[1] };
          distribution(row);
        }
      }
    });
  },
  { deep: true, immediate: true }
);

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);
</script>

<style></style>
